package com.yb.mini.common.exception;

import com.yb.mini.common.common.Result;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import java.util.stream.Collectors;

/**
 * 全局统一异常捕获处理类
 * 不再使用@ResponseStatus来进行返回响应码和响应信息,这个设置的是请求的状态码,
 * 例如使用浏览器请求时返回的响应码,使用默认即可,至于业务的状态码,就是从Result获取即可,
 * 可以把业务状态码设置为自定义的状态码
 *
 * @author yangbiao
 * @date 2023/12/18
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public Result customException(CustomException e) {
        log.error(e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result bindException(BindException e) {
        log.error(e.getMessage());
        if (!CollectionUtils.isEmpty(e.getFieldErrors())) {
            String errorMessage = e.getFieldErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(","));
            return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), errorMessage);
        }
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(),
                Result.ResultEnum.CUSTOM_EXCEPTION.getMessage());
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result constraintViolationExceptionHandler(ConstraintViolationException e) {
        log.error(e.getMessage(), e);
        if (!CollectionUtils.isEmpty(e.getConstraintViolations())) {
            String withMessage = e.getConstraintViolations()
                    .stream()
                    .map(ConstraintViolation::getMessage)
                    .collect(Collectors.joining(","));
            return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), withMessage);
        }
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(),
                Result.ResultEnum.CUSTOM_EXCEPTION.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        if (!CollectionUtils.isEmpty(e.getBindingResult().getFieldErrors())) {
            String errorMessage = e.getBindingResult().getFieldErrors().stream()
                    .map(DefaultMessageSourceResolvable::getDefaultMessage)
                    .collect(Collectors.joining(","));
            return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), errorMessage);
        }
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(),
                Result.ResultEnum.CUSTOM_EXCEPTION.getMessage());
    }

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public Result<String> maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        log.error(e.getMessage());
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "文件大小超过限制");
    }

    @ExceptionHandler({HttpMessageNotReadableException.class})
    public Result httpMessageNotReadableException(HttpMessageNotReadableException e) {
        log.error(e.getMessage(), e);
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "请求参数无法解析");
    }

    @ExceptionHandler(HttpMessageNotWritableException.class)
    public Result httpMessageNotWritableExceptionHandler(HttpMessageNotWritableException e) {
        log.error(e.getMessage(), e);
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "响应数据无法解析");
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public Result methodArgumentTypeMismatchExceptionHandler(HttpRequestMethodNotSupportedException e) {
        log.error(e.getMessage(), e);
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "请求方法不支持,请检查请求方式是否不匹配");
    }

    @ExceptionHandler({MethodArgumentTypeMismatchException.class})
    public Result methodArgumentTypeMismatchExceptionHandler(MethodArgumentTypeMismatchException e) {
        log.error(e.getMessage(), e);
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "参数类型不匹配或参数有误");
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result missingServletRequestParameterExceptionHandler(MissingServletRequestParameterException e) {
        log.error(e.getMessage(), e);
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "请求缺少必要的参数");
    }

    @ExceptionHandler(Exception.class)
    public Result exceptionHandler(Exception e) {
        log.error(e.getMessage(), e);
        if (e instanceof CustomException) {
            return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), e.getMessage());
        }
        return Result.error(Result.ResultEnum.CUSTOM_EXCEPTION.getCode(), "网络繁忙...");
    }

}